package com.by.service.impl;

import com.by.bean.FreightInquiry;
import com.by.common.bean.PageBean;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.utils.Assert;
import com.by.common.utils.DateUtils;
import com.by.mapper.FreightInquiryMapper;
import com.by.mapper.FreightProductMapper;
import com.by.query.FreightInquiryQuery;
import com.by.service.FreightInquiryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Service
public class FreightInquiryServiceImpl extends BaseServiceImpl<FreightInquiry,FreightInquiryMapper> implements FreightInquiryService {
    @Autowired
    FreightInquiryMapper freightInquiryMapper;
    @Autowired
    FreightProductMapper freightProductMapper;
    String maxCode;//最大编码

    @Transactional
    @Override
    public int save(FreightInquiry entity) {
        //生成编码
        String sn = generateNewCode();
        //设置编码
        entity.setQuote_coding(sn);
        //保存货代询价清单
        int res=super.save(entity);
        Assert.isZero(res,"保存货代询价单失败");
        //保存产品
        if(null!=entity.getFreightProducts()&&entity.getFreightProducts().size()>0){
            res=freightProductMapper.batchSave(sn,entity.getFreightProducts());
            Assert.isZero(res,"保存货代询价产品失败");
        }
        return 1;
    }

    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public PageBean query(FreightInquiryQuery query) {
        PageHelper.startPage(query.getPage(),query.getPageSize());
        List list = freightInquiryMapper.query(query);
        PageInfo info=new PageInfo(list);
        return new PageBean(query.getPage(),query.getPageSize(),info.getTotal(),list);
    }

    @Override
    public FreightInquiry get(String quote_coding) {
        return freightInquiryMapper.get(quote_coding);
    }
    String generateNewCode(){
        String ym= DateUtils.getSystemTimeYM();
        //判断最大编码是否存在
        if(null==maxCode){
            //如果不存在查询数据库
            maxCode= freightInquiryMapper.queryMaxCode();
            if(null==maxCode){
                maxCode = "XJ" + ym + "0001";
                return maxCode;
            }
        }
        //执行到这里  获取最大编码 XJ25020001  计算新的编码
        //提取编码中的日期  2502
        String tmpYm = maxCode.substring(2, 6);
        if (!ym.equals(tmpYm)) {
            //说明当前最大编码不是当月的编码
            maxCode = "XJ" + ym + "0001";
            return maxCode;
        }
        //如果到这里 是当月的最大编码  序号累加 XJ25020001
        String prefix = maxCode.substring(0, 6);
        String seq = maxCode.substring(6);
        int num = Integer.parseInt(seq);
        num++;
        maxCode = prefix + String.format("%04d", num);
        return maxCode;
    }
}
